package com.rtx.edi.system.user.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rtx.edi.system.user.service.UserServices;
import com.rtx.model.dto.response.EdiResponse;
import com.rtx.model.emums.EnumDataType;
import com.rtx.model.emums.ExceptionCodeEnum;
import com.rtx.model.po.entity.system.User;
import com.rtx.model.po.entity.system.UserPermission;
import com.rtx.model.po.service.UserDAO;
import com.rtx.model.po.service.UserPermissionDAO;

@Service
public class UserServicesImpl implements UserServices {
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	UserDAO userDAO;
	
	@Autowired
	UserPermissionDAO userPermissionDAO;

	@Override
	public EdiResponse queryUser(int currentPage,User user) {
		Page<User> page = new Page<User>(currentPage,20);
		LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<User>();
		if(StringUtils.hasLength(user.getUsername())) {
			qw.like(User::getUsername, user.getUsername());
		}
		if(StringUtils.hasLength(user.getEmail())) {
			qw.like(User::getEmail, user.getEmail());
		}
		
        userDAO.selectPage(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), page, qw);
		return EdiResponse.success().data("page", page);
	}
	
	

	
	@Override
	public EdiResponse queryusebyid(User user) {
		LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<User>();
		qw.eq(User::getId, user.getId());
		List<User> list = userDAO.selectUserByQueryCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), qw);
		return EdiResponse.success().data("item", list.get(0));
	}

	@Override
	public EdiResponse queryUserByUsername(String username) {
		LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<User>();
		qw.eq(User::getUsername, username);
		List<User> list =	userDAO.selectUserByQueryCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), qw);
		return EdiResponse.success().data("data", list.get(0));
	}


	@Override
	public EdiResponse insert(User user) {
		EdiResponse response = new EdiResponse();
		LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<User>();
		qw.eq(User::getUsername, user.getUsername());
		List<User> list =	userDAO.selectUserByQueryCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), qw);		
		if(list.size() >0) {
			user.setId(list.get(0).getId());
			userDAO.updateByCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), user);
		}else {
            if (user.getUsername() == null || "".equals(user.getUsername())) {
                response.setReturnCode(400);
                response.setReturnMgr(ExceptionCodeEnum.EXC_000647.getCode());
            } else if (user.getPassword() == null || "".equals(user.getPassword())) {
                response.setReturnCode(400);
                response.setReturnMgr(ExceptionCodeEnum.EXC_000648.getCode());
            } else if (user.getFullname() == null || "".equals(user.getFullname())) {
            	response.setReturnCode(400);
                response.setReturnMgr(ExceptionCodeEnum.EXC_000649.getCode());
            } else {
                ByteSource salt = ByteSource.Util.bytes(user.getUsername() + user.getPassword());
                SimpleHash result = new SimpleHash("MD5", user.getPassword(), salt, 1024);
                user.setSalt(salt.toString());
                user.setPassword(result.toString());
                user.setCreatetime(new Date());
                user.setUserLanguage("zh");
                user.setLocked(1);
                userDAO.insert(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), user);
                response =  EdiResponse.success();
            }
		}
		response.setReturnCode(200);
		response.setReturnMgr("success");
		return response;
	}


	@Override
	public EdiResponse deleteByusername(List<String> usernames) {
		
		EdiResponse response = new EdiResponse();
        try {
            for (String key : usernames) {
            	
        		LambdaQueryWrapper<User> qw = Wrappers.lambdaQuery();
        		qw.eq(User::getUsername, key);
        		List<User> list =	userDAO.selectUserByQueryCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), qw);	
        		
        		for(User user:list) {
        			LambdaQueryWrapper<UserPermission> up = Wrappers.lambdaQuery();
            		up.eq(UserPermission::getUserId, user.getId());
            		userPermissionDAO.deleteByCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), up);
        		}
        		
                //删除用户信息
        		userDAO.deleteByusername(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), key);
        		response.setReturnCode(200);
        		response.setReturnMgr("success");
            }
        } catch (Exception e) {
            log.error("", e);
            response.setReturnCode(400);
            response.setReturnMgr(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return response;
		
	}


	@Override
	public EdiResponse updatStatus(String[] username) {
		EdiResponse response = new EdiResponse();

        for (String key : username) {
        	
    		LambdaQueryWrapper<User> qw = Wrappers.lambdaQuery();
    		qw.eq(User::getUsername, key);
    		List<User> list =	userDAO.selectUserByQueryCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), qw);	
    		
    		for(User user:list) {
    			User updUser = new User();
    			updUser.setId(user.getId());
    			updUser.setStatus(-user.getStatus());
    			userDAO.updateByCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), updUser);
    		}
    		
        }
        
		response.setReturnCode(200);
		response.setReturnMgr("success");
		return response;
	}
}
